<template>
  <!-- 主弹窗 -->
  <el-dialog
      v-model="dialogVisible"
      title="修改用户信息"
      width="800px"
      :before-close="handleClose"
      @open="handleDialogOpen"
  >
    <div v-loading="loading">
      <div class="text-center">
        <UserAvatar />
      </div>
      <el-form :model="formData" label-width="100px" ref="formRef">
        <!-- 基本信息 -->
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户昵称" prop="nickName"
                          :rules="[{ required: true, message: '请输入用户昵称', trigger: 'blur' }]">
              <el-input v-model="formData.nickName" placeholder="请输入用户昵称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户性别" prop="sex">
              <el-select v-model="formData.sex" placeholder="请选择性别">
                <el-option label="男" value="0" />
                <el-option label="女" value="1" />
                <el-option label="未知" value="2" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 联系信息 -->
        <el-row>
          <el-col :span="12">
            <el-form-item label="手机号码">
              <!-- 使用 el-text 展示手机号 -->
              <el-text class="mx-1" size="large">{{ formData.phonenumber || '未填写' }}</el-text>
              <el-button @click="showPhoneDialog" type="primary" link style="margin-left: 10px;">
                修改
              </el-button>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱">
              <!-- 使用 el-text 展示邮箱 -->
              <el-text class="mx-1" size="large">{{ formData.email || '未填写' }}</el-text>
              <el-button @click="showEmailDialog" type="primary" link style="margin-left: 10px;">
                修改
              </el-button>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 用户详情信息 -->
        <el-row>
          <el-col :span="12">
            <el-form-item label="常驻地区">
              <el-input v-model="formData.region" placeholder="请输入常驻地区" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工作行业">
              <el-input v-model="formData.industry" placeholder="请输入工作行业" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="体重(kg)">
              <el-input-number
                  v-model="formData.weight"
                  :min="0"
                  :max="200"
                  :precision="2"
                  controls-position="right"
                  placeholder="请输入体重"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出生年月">
              <el-date-picker
                  v-model="formData.birthDate"
                  type="date"
                  placeholder="选择日期"
                  value-format="YYYY-MM-DD"
                  style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <template #footer>
      <el-button type="warning" @click="handlePwdOpen">修改密码</el-button>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="submitting">
        保存
      </el-button>
    </template>
  </el-dialog>

  <!-- 手机号修改弹窗 -->
  <el-dialog v-model="phoneDialogVisible" title="修改手机号" width="400px">
    <el-form :model="phoneForm" label-width="80px" ref="phoneFormRef">
      <el-form-item label="新手机号" prop="newPhone"
                    :rules="[{
            required: true, pattern: /^1[3-9]\d{9}$/,
            message: '请输入正确的手机号',
            trigger: 'blur'
        }]">
        <el-input v-model="phoneForm.newPhone" placeholder="请输入新手机号" />
      </el-form-item>
      <el-form-item label="验证码" prop="code"
                    :rules="[{ required: true, message: '请输入验证码', trigger: 'blur' }]">
        <el-input v-model="phoneForm.code" placeholder="请输入验证码" maxlength="6">
          <template #append>
            <el-button :disabled="phoneCodeDisabled" @click="sendPhoneCode" type="primary">
              {{ phoneCodeText }}
            </el-button>
          </template>
        </el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="phoneDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="updatePhone" :loading="phoneLoading">
        确定
      </el-button>
    </template>
  </el-dialog>

  <!-- 邮箱修改弹窗 -->
  <el-dialog v-model="emailDialogVisible" title="修改邮箱" width="400px">
    <el-form :model="emailForm" label-width="80px" ref="emailFormRef">
      <el-form-item label="新邮箱" prop="newEmail"
                    :rules="[
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
        ]">
        <el-input v-model="emailForm.newEmail" placeholder="请输入新邮箱" />
      </el-form-item>
      <el-form-item label="验证码" prop="code"
                    :rules="[{ required: true, message: '请输入验证码', trigger: 'blur' }]">
        <el-input v-model="emailForm.code" placeholder="请输入验证码" maxlength="6">
          <template #append>
            <el-button :disabled="emailCodeDisabled" @click="sendEmailCode" type="primary">
              {{ emailCodeText }}
            </el-button>
          </template>
        </el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="emailDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="updateEmail" :loading="emailLoading">
        确定
      </el-button>
    </template>
  </el-dialog>
  <el-dialog title="修改密码" v-model="pwdDialogVisible" :before-close="handlePwdClose">
    <ResetPwd ref="pwdFormRef" />
  </el-dialog>
</template>

<script setup>
import { ref, reactive, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import {
  getEmailCode,
  getPhoneCode,
  getUserDetail,
  updateUserDetail,
  updateUserEmail,
  updateUserPhone
} from "@/api/user/commonUser.js";
import UserAvatar from "@/views/system/user/profile/userAvatar.vue";
import ResetPwd from "@/views/system/user/profile/resetPwd.vue";
// 弹窗显示控制
const dialogVisible = ref(false)
const phoneDialogVisible = ref(false)
const emailDialogVisible = ref(false)
const pwdDialogVisible = ref(false)
const pwdFormRef = ref()
// 当前用户ID
const currentUserId = ref(null)

// 加载状态
const loading = ref(false)
const submitting = ref(false)
const phoneLoading = ref(false)
const emailLoading = ref(false)

// 表单引用
const formRef = ref()
const phoneFormRef = ref()
const emailFormRef = ref()

// 表单数据
const formData = reactive({
  // sys_user 表可修改字段
  nickName: '',
  sex: '0',
  phonenumber: '',
  email: '',

  // sys_user_detail 表字段
  region: '',
  industry: '',
  weight: null,
  birthDate: ''
})

// 手机号修改表单
const phoneForm = reactive({
  newPhone: '',
  code: '',
  uuid: ''
})

// 邮箱修改表单
const emailForm = reactive({
  newEmail: '',
  code: '',
  uuid: ''
})

// 验证码相关
const phoneCodeDisabled = ref(false)
const phoneCodeText = ref('获取验证码')
let phoneCountdown = 60

const emailCodeDisabled = ref(false)
const emailCodeText = ref('获取验证码')
let emailCountdown = 60

// 获取用户详情信息
const fetchUserDetail = async (userId) => {
  try {
    loading.value = true
    // 实际API调用
    const response = await getUserDetail(userId)
    console.log('获取用户详情成功:', response)
    // 填充表单数据
    Object.keys(formData).forEach(key => {
      if (response.data[key] !== undefined) {
        formData[key] = response.data[key]
      }
    })

    currentUserId.value = userId
  } catch (error) {
    ElMessage.error('获取用户信息失败')
    console.error('获取用户详情失败:', error)
  } finally {
    loading.value = false
  }
}

// 打开弹窗方法（暴露给父组件）
const openDialog = (userId) => {
  if (!userId) {
    ElMessage.error('用户ID不能为空')
    return
  }

  dialogVisible.value = true
  currentUserId.value = userId
}

// 弹窗打开时的处理
const handleDialogOpen = () => {
  if (currentUserId.value) {
    fetchUserDetail(currentUserId.value)
  }
}

// 关闭弹窗
const handleClose = () => {
  dialogVisible.value = false
  resetForm()
}

// 重置表单
const resetForm = () => {
  formRef.value?.resetFields()
  currentUserId.value = null
  Object.keys(formData).forEach(key => {
    if (typeof formData[key] === 'string') {
      formData[key] = ''
    } else if (typeof formData[key] === 'number') {
      formData[key] = null
    }
  })
}

// 显示手机号修改弹窗
const showPhoneDialog = () => {
  phoneForm.newPhone = formData.phonenumber
  phoneDialogVisible.value = true
  nextTick(() => {
    phoneFormRef.value?.clearValidate()
  })
}

// 显示邮箱修改弹窗
const showEmailDialog = () => {
  emailForm.newEmail = formData.email
  emailDialogVisible.value = true
  nextTick(() => {
    emailFormRef.value?.clearValidate()
  })
}

// 发送手机验证码
const sendPhoneCode = async () => {
  try {
    await phoneFormRef.value.validateField('newPhone')

    phoneCodeDisabled.value = true
    const timer = setInterval(() => {
      phoneCodeText.value = `${phoneCountdown}秒后重新发送`
      phoneCountdown--

      if (phoneCountdown < 0) {
        clearInterval(timer)
        phoneCodeDisabled.value = false
        phoneCodeText.value = '获取验证码'
        phoneCountdown = 60
      }
    }, 1000)

    // 调用发送验证码接口
    const response=await getPhoneCode(phoneForm.newPhone)
    console.log('发送验证码成功:', response)
    phoneForm.uuid = response.uuid
    ElMessage.success(response.context)
  } catch (error) {
    ElMessage.warning('请填写正确的手机号')
    console.error('发送验证码失败:', error)
  }
}

// 发送邮箱验证码
const sendEmailCode = async () => {
  try {
    await emailFormRef.value.validateField('newEmail')

    emailCodeDisabled.value = true
    const timer = setInterval(() => {
      emailCodeText.value = `${emailCountdown}秒后重新发送`
      emailCountdown--

      if (emailCountdown < 0) {
        clearInterval(timer)
        emailCodeDisabled.value = false
        emailCodeText.value = '获取验证码'
        emailCountdown = 60
      }
    }, 1000)

    // 调用发送邮箱验证码接口
    const response= await getEmailCode(emailForm.newEmail)
    emailForm.uuid = response.uuid
    ElMessage.success(response.context)
  } catch (error) {
    ElMessage.warning('请填写正确的邮箱')
    console.error('发送验证码失败:', error)
  }
}

// 更新手机号
const updatePhone = async () => {
  try {
    await phoneFormRef.value.validate()

    phoneLoading.value = true
    // 调用更新手机号接口
    await updateUserPhone({
      payload: phoneForm.newPhone,
      code: phoneForm.code,
      uuid: phoneForm.uuid
    })

    formData.phonenumber = phoneForm.newPhone
    phoneDialogVisible.value = false
    phoneFormRef.value.resetFields()
    ElMessage.success('手机号修改成功')
  } catch (error) {
    ElMessage.error('手机号修改失败')
  } finally {
    phoneLoading.value = false
  }
}

// 更新邮箱
const updateEmail = async () => {
  try {
    await emailFormRef.value.validate()

    emailLoading.value = true
    // 调用更新邮箱接口
    await updateUserEmail({
      payload: emailForm.newEmail,
      code: emailForm.code,
      uuid: emailForm.uuid
    })

    formData.email = emailForm.newEmail
    emailDialogVisible.value = false
    emailFormRef.value.resetFields()
    ElMessage.success('邮箱修改成功')
  } catch (error) {
    ElMessage.error('邮箱修改失败')
  } finally {
    emailLoading.value = false
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    submitting.value = true
    await updateUserDetail(formData)

    ElMessage.success('用户信息修改成功')
    dialogVisible.value = false

    // 可以触发父组件刷新数据
    // emit('success')
  } catch (error) {
    ElMessage.error('表单验证失败')
  } finally {
    submitting.value = false
  }
}
const handlePwdOpen=()=>{
  pwdDialogVisible.value=true
}
const handlePwdClose=()=>{
  pwdFormRef.value.resetForm()
  pwdDialogVisible.value=false
}
// 暴露方法给父组件
defineExpose({
  openDialog
})
</script>